package cn.conac.rc.file.service;

import cn.conac.rc.file.entity.AppFilesEntity;
import cn.conac.rc.file.entity.FileEntity;
import cn.conac.rc.file.repository.AppFilesRepository;
import cn.conac.rc.file.repository.FileRepository;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.framework.utils.ResponseUtils;
import cn.conac.rc.framework.vo.ResultPojo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Service
public class FileService extends GenericService<FileEntity, Integer> {

	@Autowired
	private FileRepository fileRepository;

	@Autowired
	private AppFilesRepository appFilesRepository;
	
	/**
	 * 保存文件相关信息到数据库
	 * @param appFiles
	 * @return AppFilesEntity
	 */
	public AppFilesEntity saveFileInfo(AppFilesEntity appFiles){
		// 保存文件到数据库
		return appFilesRepository.save(appFiles);
	}

	/**
	 * 下载文件到指定位置
	 * 
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @param fileId 文件ID
	 * @return ResultPojo 下载结果Bean
	 */
	public ResultPojo download(HttpServletRequest request, HttpServletResponse response, Integer fileId) throws Exception {
		ResultPojo result = new ResultPojo();
		if(fileId!=null){
			FileEntity rcFile = fileRepository.findById(fileId);
			if(null != rcFile){
				// 设置绝对路径
				String absolutePath = StringUtils.isNotBlank(rcFile.getAbsolutePath())?rcFile.getAbsolutePath():StringUtils.EMPTY;
				// 设置相对路径
				String relativePath = StringUtils.isNotBlank(rcFile.getRelativePath())?rcFile.getRelativePath():StringUtils.EMPTY;
				// 拼装完整路径
				String filePath = absolutePath + relativePath;
				String fileName = rcFile.getFileName();
				if(StringUtils.isNotBlank(filePath) && StringUtils.isNotBlank(fileName)){
					// 文件绝对路径获取
					File srcFile = new File(filePath);
					if(srcFile.exists()){
						ResponseUtils.download(request,response,fileName,srcFile);

						result.setCode(ResultPojo.CODE_SUCCESS);
						result.setMsg("文件下载成功！");
						result.setResult(srcFile.length());
						return result;
					}
				}
			}
		}
		result.setCode(ResultPojo.CODE_FAILURE);
		result.setMsg("文件信息获取时出错、下载失败！ID:"+fileId);
		return result;
	}
	
	/**
	 * 根据文件ID检索文件信息
	 * 
	 * @param id 文件ID
	 * @return 相关文件信息
	 */
	public FileEntity searchFileById(Integer id) {
		return fileRepository.findById(id);
	}

}

